<template>
  <el-upload
    :file-list="curFileList"
    action
    :http-request="uploadImg"
    list-type="picture-card"
    :on-preview="handlePictureCardPreview"
    :on-remove="handleRemove"
    :on-success="handleSuccess"
    :class="{
      imgHide: type === DialogType.detail,
      uploadHide: curFileList.length > 0,
    }"
  >
  <div class="inline-box">
    <el-icon><Plus /></el-icon>
    <span v-if="!!tips" style="color: red; font-size: 12px;">{{ tips }}</span>
  </div>
  </el-upload>

  <el-dialog v-model="dialogVisible">
    <img w-full :src="dialogImageUrl" alt="Preview Image" />
  </el-dialog>
</template>

<script lang="ts" setup>
import {
  nextTick,
  Ref,
  ref,
  defineExpose,
  defineProps,
  computed,
  watch,
} from "vue";
import { Plus } from "@element-plus/icons-vue";
import { upload, getImg } from "@/api/common";

import type { UploadProps } from "element-plus";
import { DialogType } from "@/utils/types";
const props = defineProps({
  url: {
    type: String,
    default: "",
  },
  type: {
    type: Number,
    default: 1,
  },
  tips: {
    type: String,
    default: '',
  },
});
const dialogImageUrl = ref("");
const dialogVisible = ref(false);
const curFileList = computed(() => {
  return props.url ? [{ url: props.url }] : [];
});
const emit = defineEmits(["addImgKey","delImgKey"]);
const handleRemove: UploadProps["onRemove"] = (uploadFile, uploadFiles) => {
  emit("delImgKey");
};
const handlePictureCardPreview: UploadProps["onPreview"] = (uploadFile) => {
  dialogImageUrl.value = uploadFile.url!;
  dialogVisible.value = true;
};
const uploadImg = (f: any) => {
  let param = new FormData(); //创建form对象
  param.append("file", f.file); //通过append向form对象添加数据
  param.append("type", "INDEX_PIC"); //添加form表单中其他数据
  return upload(param);
};
const handleSuccess = (uploadFile: any) => {
  emit("addImgKey", uploadFile.value.url, uploadFile.value.key);
};
defineExpose({});
</script>
<style lang="scss">
.el-upload--picture-card {
  --el-upload-picture-card-size: 148px;
  background-color: var(--el-fill-color-lighter);
  border: 1px dashed var(--el-border-color-darker);
  border-radius: 6px;
  box-sizing: border-box;
  width: var(--el-upload-picture-card-size);
  height: var(--el-upload-picture-card-size);
  cursor: pointer;
  vertical-align: top;
  display: inline-flex;
  justify-content: center;
  align-items: center;
  margin-right: 10px;
}
.imgHide .el-upload--picture-card {
  display: none;
}
.uploadHide {
  .el-upload.el-upload--picture-card {
    display: none;
  }
}
.inline-box {
  display: flex;
  flex-direction: column;
  align-items: center;
  vertical-align: middle;
  justify-content: space-around;
}
</style>
